package com.ymatou.iapi.csim.testcase;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.http.client.ClientProtocolException;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import com.ymatou.iapi.csim.parameter.CsMessageDto;
import com.ymatou.iapi.csim.parameter.GetCsMessageListResp;
import com.ymatou.iapi.csim.parameter.GetMessageListBean;
import com.ymatou.iapi.csim.parameter.GetUserMessageListResp;
import com.ymatou.iapi.csim.parameter.LoginBean;
import com.ymatou.iapi.csim.parameter.MessageSessionDto;
import com.ymatou.iapi.csim.parameter.OnlineBean;
import com.ymatou.iapi.csim.parameter.OpenSessionBean;
import com.ymatou.iapi.csim.parameter.SendMessageBean;
import com.ymatou.iapi.csim.parameter.SendMessageCSBean;
import com.ymatou.iapi.csim.service.GetMessageListCall;
import com.ymatou.iapi.csim.service.OpenSessionCall;
import com.ymatou.iapi.csim.service.SendMessageCSCall;
import com.ymatou.iapi.csim.service.SendMessageCall;
import com.ymatou.tool.FormatUtil;
import com.ymt.core.tool.Logger;
import com.ymt.utils.annotation.*;
import com.ymt.utils.tag.*;
import com.ymttest.business.service.CsimCallService;
import com.ymttest.business.service.JUserCallService;
import com.ymttest.database.model.Userinfo;
import com.ymttest.database.model.Userinfoex;
import com.ymttest.database.model.YmtMessage;
import com.ymttest.database.model.YmtUsers;
import com.ymttest.database.model.ymt_cssession;
import com.ymttest.database.model.ymt_onlinecs;
import com.ymttest.database.sqlwapper.ImDefaultWapper;
import com.ymttest.database.sqlwapper.JUserWapper;
import com.ymttest.database.sqlwapper.YmtUsersWapper;
import com.ymttest.database.sqlwapper.CSIM.ymt_cssessionWapper;
import com.ymttest.database.sqlwapper.CSIM.ymt_onlinecsWapper;
import com.ymttest.utils.DataUtil;
import com.ymttest.utils.EnvSetup;
import com.ymttest.utils.MapUtil;
import com.ymttest.utils.TestDataManager;
/**
*客服对买家和买手发送消息
*FreeMaker Template自动生成代码
*/
@TestSuite
public class Ts_SendMessageCS{
	private static SendMessageCSBean bean;
	private static SendMessageCSCall call;
	private CsimCallService service=new CsimCallService();
	private String customerName=EnvSetup.getData("customerName").toString(); 
	private Integer csId=Integer.parseInt(EnvSetup.getData("csId").toString());
	private Integer userId=Integer.parseInt(EnvSetup.getData("userId_IM").toString());
	private Integer sellerId1=Integer.parseInt(EnvSetup.getData("autotest_seller1").toString());
	private static ymt_cssessionWapper csSessionWapper=new ymt_cssessionWapper();
	@BeforeClass
	public static void setUp() {
		Logger.createResultFile("客服对买家和买手发送消息");
	}

	@Before
	public void caseUp() {
		bean=new SendMessageCSBean();
		call=new SendMessageCSCall();
	}

	@AfterClass
	public static void tearDown() {
		Logger.generateResult(call.getOpurl());
	}

	@After
	public void caseDown() {
		Logger.end();
	}
	@Test
	@Category({P1.class})
	@TestCase
	public void Tc_SendMessageCS_001() {
		Logger.start(true,"客服发送消息-客服主动给买家");
		try {
    		//查询是否有在线客服 1，2
    		service.getOnlineCS();
    		//打开会话
    		ymt_cssession csSession=service.getOpenSession(csId,userId);
    		
			Logger.comment("csSession.getId():"+csSession.getId());
			bean.setCsId(csId);
			bean.setUserId(userId);
            bean.setMessage("客服给买家发消息_自动化测试_"+TestDataManager.getRandomIntNum(5));
            bean.setSessionId(csSession.getId());
            bean.setAppId("imyy.ymatou.com");
			call.setData(bean);
			call.callService();		
			verifyDB();
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category({P1.class})
	@TestCase
	public void Tc_SendMessageCS_002() {
		Logger.start(true,"客服发送消息-客服主动给买手");
		try {
    		//查询是否有在线客服 1，2
    		service.getOnlineCS();
    		//打开会话
    		ymt_cssession csSession=service.getOpenSession(sellerId1,userId);
    	
    		
			Logger.comment("csSession.getId():"+csSession.getId());
			bean.setCsId(csId);
			bean.setUserId(sellerId1);
            bean.setMessage("客服给买手发消息_自动化测试_"+TestDataManager.getRandomIntNum(5));
            bean.setSessionId(csSession.getId());
            bean.setAppId("imyy.ymatou.com");
			call.setData(bean);
			call.callService();		
			verifyDB();
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	
	
	@Test
	@Category({P1.class})
	@TestCase
	public void Tc_SendMessageCS_003() {
		Logger.start(true,"客服发送消息-买家主动给客服发消息,客服回复");
		try {
			//买家发消息
			SendMessageBean sendMessageBean=service.setSendMessageBean();
			sendMessageBean.setUserId(userId);
			SendMessageCall sendMessageCall=service.setSendMessageCall(sendMessageBean);
    		
			service.getOnlineCS();
			//打开会话
    		ymt_cssession csSession=service.getOpenSession(csId,userId);
    		
			Logger.comment("csSession.getId():"+csSession.getId());
			bean.setCsId(csId);
			bean.setUserId(userId);
            bean.setMessage("客服给买家回复_自动化测试_"+TestDataManager.getRandomIntNum(5));
            bean.setSessionId(csSession.getId());
            bean.setAppId("imyy.ymatou.com");
			call.setData(bean);
			call.callService();		
			verifyDB();
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	
	@Test
	@Category({P1.class})
	@TestCase
	public void Tc_SendMessageCS_004() {
		Logger.start(true,"客服发送消息-买手主动给客服发消息,客服回复");
		try {
			//买家发消息
			int csId_seller=Integer.parseInt(EnvSetup.getData("csId_seller").toString());
			
			SendMessageBean sendMessageBean=service.setSendMessageBean();
			sendMessageBean.setUserId(sellerId1);
			SendMessageCall sendMessageCall=service.setSendMessageCall(sendMessageBean);
    		
			ymt_onlinecsWapper onlinecsWapper=new ymt_onlinecsWapper();
			//客服上线
			ymt_onlinecs onlinecs=service.getOnlineCS(csId_seller);
			//修改类型
			onlinecs.setCSType(1);
			onlinecs.setCSName("买手客服1");
			onlinecs.setCSNickName("买手昵称1");
			onlinecsWapper.updateByPrimaryKey(onlinecs);
			//打开会话
    		ymt_cssession csSession=service.getOpenSession(csId_seller,userId);
			
			Logger.comment("csSession.getId():"+csSession.getId());
			bean.setCsId(csId_seller);
			bean.setUserId(sellerId1);
            bean.setMessage("客服回复买手_自动化测试_"+TestDataManager.getRandomIntNum(5));
            bean.setSessionId(csSession.getId());
            bean.setAppId("imyy.ymatou.com");
			call.setData(bean);
			call.callService();		
			verifyDB();
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	@Test
	@Category({P1.class})
	@TestCase
	public void Tc_SendMessageCS_005() {
		Logger.start(true,"客服发送消息-消息来源是微信");
		try {
			//买家发消息
			int csId_seller=Integer.parseInt(EnvSetup.getData("csId_seller").toString());
			
			SendMessageBean sendMessageBean=service.setSendMessageBean();
			sendMessageBean.setUserId(sellerId1);
			sendMessageBean.setMessageSource(101);
			sendMessageBean.setSourceParams("微信");//微信
			SendMessageCall sendMessageCall=service.setSendMessageCall(sendMessageBean);

			ymt_onlinecsWapper onlinecsWapper=new ymt_onlinecsWapper();
			//客服上线
			ymt_onlinecs onlinecs=service.getOnlineCS(csId_seller);
			//修改类型
			onlinecs.setCSType(1);
			onlinecs.setCSName("买手客服1");
			onlinecs.setCSNickName("买手昵称1");
			onlinecsWapper.updateByPrimaryKey(onlinecs);
			//打开会话
    		ymt_cssession csSession=service.getOpenSession(csId_seller,userId);
    	
    		
			Logger.comment("csSession.getId():"+csSession.getId());
			bean.setCsId(csId_seller);
			bean.setUserId(sellerId1);
            bean.setMessage("客服回复买手_自动化测试_"+TestDataManager.getRandomIntNum(5));
            bean.setSessionId(csSession.getId());
            bean.setAppId("imyy.ymatou.com");
			call.setData(bean);
			call.callService();		
			verifyDB();
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	@Test
	@Category({P1.class})
	@TestCase
	public void Tc_SendMessageCS_006() {
		Logger.start(true,"客服发送消息-会话未开启");
		try {
    		//查询是否有在线客服 1，2
    		service.getOnlineCS();
    		//3:查询是否有会话
    		int count=csSessionWapper.selectBy_Count(MapUtil.hashMap("CSId",csId,"UserId",userId,"Status",0));
    		OpenSessionCall openSessionCall=new OpenSessionCall();
    		
    		ymt_cssession csSession=csSessionWapper.selectBy(MapUtil.hashMap("CSId",csId,"UserId",userId,"Status",0));
    		if(count>=1){
    			//修改关闭会话
    			 csSession.setStatus(1);
    			 csSessionWapper.updateByPrimaryKey(csSession);
    		}
    	
			Logger.comment("csSession.getId():"+csSession.getId());
			bean.setCsId(csId);
			bean.setUserId(userId);
            bean.setMessage("客服给买家发消息_自动化测试_"+TestDataManager.getRandomIntNum(5));
            bean.setSessionId(csSession.getId());
            bean.setAppId("imyy.ymatou.com");
			call.setData(bean);
			call.callService();		
			Logger.verifyEquals("500", call.getStatus(), "验证返回的status");
			Logger.verifyEquals(true, call.getMsg().contains("会话Id不存在"), "验证返回的Msg");
			Logger.verifyEquals("2", DataUtil.Json.parseJsonObj(call.getResult()).get("ErrorCode").toString(), "验证返回的errorCode");
			Logger.verifyEquals(true, DataUtil.Json.parseJsonObj(call.getResult()).get("ErrorMessage").toString().contains("会话Id不存在"), "验证返回的errorMessage");
			Logger.verifyEquals("false", DataUtil.Json.parseJsonObj(call.getResult()).get("Success").toString(), "验证返回的Success");
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	private void  verifyDB() throws InterruptedException, ClientProtocolException, IOException
	{
		//获取消息
		ymt_cssession cssession=csSessionWapper.selectByPrimaryKey(bean.getSessionId());
		Logger.comment("getSessionNumber:"+cssession.getSessionNumber());
		GetMessageListBean messageListBean=service.GetMessageListBean();
		messageListBean.setSessionNumber(cssession.getSessionNumber());
		messageListBean.setToUserId(bean.getUserId());
		GetMessageListCall getMessgeListcall=service.GetMessageListCall(messageListBean);
		GetUserMessageListResp resp=getMessgeListcall.getData();
		JUserWapper userWapper=new JUserWapper();
		//YmtMessageSession
		MessageSessionDto messageSession=resp.getYmtMessageSession();
		Logger.verifyEquals(messageSession.getUserSessionId(), messageListBean.getFromuserId()+"_"+bean.getUserId(), "验证返回的UserSessionId");
		Logger.verifyEquals(messageSession.getMessageType(),0, "验证返回的MessageType");
		Logger.verifyEquals(messageSession.getFromUserLogo(),"http://staticontent.ymatou.com/app/userlogo/mj.jpg", "验证返回的FromUserLogo");
		Logger.verifyEquals(messageSession.getFromUserName(),"洋管家SIT", "验证返回的FromUserName");
		//更新会话最后发送消息时间及清除未读数
//		Logger.verifyEquals(true,Math.abs(cssession.getLastMessageTime().getTime() - new Date().getTime()) <= 10 * 1000 ,
//				"验证返回的最后更新时间与当前时间误差应不超过3秒");
		Logger.verifyEquals(cssession.getUnReadCount(),0, "验证返回的UnReadCount");
		Userinfo userInfo1=userWapper.selectUserinfoByUid(bean.getUserId()).get(0);
		String userLogoUrl=new JUserCallService().GetLogoUrl(bean.getUserId());
		Logger.verifyEquals(messageSession.getToUserName(),userInfo1.getLoginId(), "验证返回的UserName");
		Logger.verifyEquals(messageSession.getToUserLogo(),userLogoUrl, "验证返回的UserLogo");
		//YmtMessageList
		resp.getYmtMessageList().stream().filter(t->t.getMessage().equals(bean.getMessage()))
				.collect(Collectors.toList()).forEach(
						x->{
							Logger.verifyEquals(x.getMsgFromId(), messageListBean.getFromuserId(), "验证返回的MsgFromId");
							Logger.verifyEquals(x.getMsgToId(), messageListBean.getToUserId(), "验证返回的MsgToId");
							Logger.verifyEquals(x.getMessage(), bean.getMessage(), "验证返回的Message");
							Logger.verifyEquals(x.getIsRead(), 0, "验证返回的IsRead");
							Logger.verifyEquals(x.getMsgFrom(), customerName, "验证返回的MsgFrom");
							//查询userInfo
							try {
								Userinfo userInfo=userWapper.selectUserinfoByUid(x.getMsgToId()).get(0);
								Userinfoex userInfoex=userWapper.selectUserinfoexByUid(x.getMsgToId()).get(0);
								//Logger.verifyEquals(x.getToUserType(), userInfo.getUserType(), "验证返回的ToUserType");
								//Logger.verifyEquals(x.getUserLoginId(), userInfo.getLoginId(), "验证返回的UserLoginId");
								Logger.verifyEquals(x.getUserLogoUrl(), userInfoex.getLogoUrl(), "验证返回的UserLogoUrl");
								Logger.verifyEquals(x.getMsgTo(), userInfo.getLoginId(), "验证返回的MsgTo");
							} catch (Exception e) {
								e.printStackTrace();
							}
							Logger.verifyEquals(x.getRsee(), 0, "验证返回的Rsee");
							Logger.verifyEquals(x.getSsee(), 0, "验证返回的Ssee");
							Logger.verifyEquals(x.getAutoReply(), 0, "验证返回的AutoReply");
							Logger.verifyEquals(cssession.getSessionNumber(), x.getSessionNumber(), "验证返回的sessionNumber");
							//MessageAttachList
						  }
						);
	}
}